//
//  ChannelControlClient.m
//  gzline
//
//  Created by hsm on 3/26/13.
//
//

#import "PokerControlClient.h"
#import "AppDelegate.h"
#import "IDGenerator.h"
#import "NSDataInfo.h"
#import "Global.h"
#import "RemoteControlClient.h"
#import "DeviceInfo.h"
#import "DataManager.h"

#define Ping_duration 5

@implementation PokerControlClient
@synthesize netEventHandler,net_deviceName;
@synthesize ctrlIP, ctrlPort,c2sPingContent, curIpList, curSocketIpList;
@synthesize isRemote;
- (id)init {
    self = [super init];
    
    netEventHandler = [[PokerNetEventHandler alloc] init];
    netEventHandler.deletate = self;
    netDataArray = [[NSMutableArray alloc] init];
    curIpList = [[NSMutableDictionary alloc] init];
    curSocketIpList = [[NSMutableDictionary alloc] init];
    remote_idDic = [[NSMutableDictionary alloc] init];
    
    self.ctrlPort = @"16038";
    ping_time = Ping_duration;
    NSString *cmdPath  = [[NSBundle mainBundle] pathForResource:@"app_cmd" ofType:@"xml"];
    NSData *cmdData = [NSData dataWithContentsOfFile:cmdPath];
    NSString *cmdStr = [[NSString alloc] initWithData:cmdData encoding:NSUTF8StringEncoding];
    self.c2sPingContent = [cmdStr stringByAppendingFormat:@"<app_cmd cmd=\"%@\"/>", @"2"];
    
    
    return self;
}
-(void)c2sPing {
    NSLog(@"c2sping xxxxx : %@", self.ctrlIP);
    if ([self.ctrlIP length] > 0) {
        [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(c2sPing) object:nil];
        [self performSelector:@selector(c2sPing) withObject:nil afterDelay:ping_time];
        [netDataArray removeAllObjects];
        [netDataArray addObject:self.c2sPingContent];
        if (netDataArray.count == 1) {
            [self openStream];
        }
    }
}
- (void)dealloc{
//    [NC removeObserver:self];
}

+(PokerControlClient*)share {
    static  PokerControlClient *instance=nil;
    if (instance==nil) {
        instance = [PokerControlClient new];
    }
    return instance;
}

-(void)openStream {
    NSLog(@"openStream %@: %@", self.ctrlIP, ctrlPort);
    self.ctrlPort = @"16038";
    [netEventHandler connectToHost:ctrlIP onPort:[ctrlPort intValue]];
}
//cmd=@"1" 学习 cmd=@"5" 手机发送遥控码 2 心跳 0 取消配置
-(void) startCmd: (NSString *)cmd code:(NSString*)code{
    if (isRemote) {
        NSLog(@"net_deviceName : %@", net_deviceName);
        if ([cmd isEqualToString:@"1"] || [cmd isEqualToString:@"9"]) {
            [[RemoteControlClient share] startRemoteCmd:0x10 sec:0x07 dataStr:net_deviceName];// 学习
        }else if ([cmd isEqualToString:@"0"]) {
            [[RemoteControlClient share] startRemoteCmd:0x10 sec:0x08 dataStr:net_deviceName];// 取消学习
        }else if ([cmd isEqualToString:@"5"]) {
            NSString *string = [NSString stringWithFormat:@"[%@,%@]", net_deviceName, code];
            NSLog(@"code : %@", string);
            [[RemoteControlClient share] startRemoteCmd:0x10 sec:0x06 dataStr:string];//遥控码
        }else if ([cmd isEqualToString:@"11"]) {//系统时间0x1011
            NSDateFormatter *formatter	=  [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
            NSString *strCurTime = [formatter stringFromDate:[NSDate date]];
            NSString *string = [NSString stringWithFormat:@"[%@,%@]", net_deviceName, strCurTime];
            NSLog(@"code : %@", string);
            [[RemoteControlClient share] startRemoteCmd:0x10 sec:0x11 dataStr:string];
        }else if ([cmd isEqualToString:@"19"]) {////返回手机开关、延时及定时列表
            NSString *string = [NSString stringWithFormat:@"[%@]", net_deviceName];
            NSLog(@"code : %@", string);
            [[RemoteControlClient share] startRemoteCmd:0x11 sec:0x05 dataStr:string];
        }else if ([cmd isEqualToString:@"100"]) {//设备是否在线
            NSString *string = [NSString stringWithFormat:@"[%@]", net_deviceName];
            NSLog(@"code : %@", string);
            [[RemoteControlClient share] startRemoteCmd:0x11 sec:0x04 dataStr:string];
        }
    }else{
        NSString *cmdPath  = [[NSBundle mainBundle] pathForResource:@"app_cmd" ofType:@"xml"];
        NSData *cmdData = [NSData dataWithContentsOfFile:cmdPath];
        NSString *cmdStr = [[NSString alloc] initWithData:cmdData encoding:NSUTF8StringEncoding];
        NSString *cmdContent = [cmdStr stringByAppendingFormat:@"<app_cmd cmd=\"%@\"/>", cmd];
        if (code) {
            ping_time = Ping_duration*10;
            [Global enableVibrate];
            cmdContent = [cmdContent stringByAppendingFormat:@"<app_data code=\"%@\"/>", code];
        }
        beginStudy = NO;
        if ([cmd intValue]==1 || [cmd intValue]==9) {//1开始学习，9射频学习
            ping_time = Ping_duration;
            beginStudy = YES;
            [self performSelector:@selector(c2sPing) withObject:nil afterDelay:3];
        }else if ([cmd intValue] == 11) {//手机当前时间
            NSDateFormatter *formatter	=  [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
            NSString *strCurTime = [formatter stringFromDate:[NSDate date]];
            cmdContent = [cmdContent stringByAppendingFormat:@"<app_data time=\"%@\"/>", strCurTime];
        }
        [netDataArray addObject:cmdContent];
        if (netDataArray.count <= 1) {
            [self openStream];
        }
    }
}
//cmd =13 插座开关
-(void) startOnOff: (NSString *)cmd code:(NSString*)code{
    if (isRemote) {
        NSLog(@"net_deviceName : %@", net_deviceName);
        if ([cmd integerValue] == 13) {
            NSString *string = [NSString stringWithFormat:@"[%@,%@]", net_deviceName, code];
            NSLog(@"code : %@", string);
            [[RemoteControlClient share] startRemoteCmd:0x11 sec:0x01 dataStr:string];//关
        }
    }else{
        NSString *cmdPath  = [[NSBundle mainBundle] pathForResource:@"app_cmd" ofType:@"xml"];
        NSData *cmdData = [NSData dataWithContentsOfFile:cmdPath];
        NSString *cmdStr = [[NSString alloc] initWithData:cmdData encoding:NSUTF8StringEncoding];
        NSString *cmdContent = [cmdStr stringByAppendingFormat:@"<app_cmd cmd=\"%@\"/>", cmd];
        if (code) {
            ping_time = Ping_duration*10;
            [Global enableVibrate];
            cmdContent = [cmdContent stringByAppendingFormat:@"<app_data on-off=\"%@\"/>", code];
        }
        [netDataArray addObject:cmdContent];
        if (netDataArray.count <= 1) {
            [self openStream];
        }
    }
}
-(void) startDelayOnOff: (NSString *)cmd code:(NSString*)code time:(NSString*)time{
    if (isRemote) {
        NSString *string = nil;
        if ([code isEqualToString:@"on"]) {
            string = [NSString stringWithFormat:@"[%@,%@]", net_deviceName, code];
            [[RemoteControlClient share] startRemoteCmd:0x11 sec:0x01 dataStr:string];//开
        }else if ([code isEqualToString:@"off"]) {
            string = [NSString stringWithFormat:@"[%@,%@]", net_deviceName, code];
            [[RemoteControlClient share] startRemoteCmd:0x11 sec:0x01 dataStr:string];//关
        }else if ([cmd isEqualToString:@"15"]) {//定时
            string = [NSString stringWithFormat:@"[%@,%@,%@]", net_deviceName, code, time];
            [[RemoteControlClient share] startRemoteCmd:0x11 sec:0x02 dataStr:string];
        }else if ([cmd isEqualToString:@"17"]) {//延时
            string = [NSString stringWithFormat:@"[%@,%@,%@]", net_deviceName, code, time];
            [[RemoteControlClient share] startRemoteCmd:0x11 sec:0x03 dataStr:string];
        }
        NSLog(@"devicename: %@ code : %@", net_deviceName, string);
    }else{
        NSString *cmdPath  = [[NSBundle mainBundle] pathForResource:@"app_cmd" ofType:@"xml"];
        NSData *cmdData = [NSData dataWithContentsOfFile:cmdPath];
        NSString *cmdStr = [[NSString alloc] initWithData:cmdData encoding:NSUTF8StringEncoding];
        NSString *cmdContent = [cmdStr stringByAppendingFormat:@"<app_cmd cmd=\"%@\"/>", cmd];
        if (code) {
            ping_time = Ping_duration*10;
            [Global enableVibrate];
            if ([cmd isEqualToString:@"17"]) {//延时
                cmdContent = [cmdContent stringByAppendingFormat:@"<app_data on-off_delay1=\"%@\" delay1s=\"%@\"/>", code, time];
            }else if ([cmd isEqualToString:@"15"]) {//定时
                cmdContent = [cmdContent stringByAppendingFormat:@"<app_data on-off01=\"%@\" timing01=\"%@\"/>", code, time];
            }
        }
        [netDataArray addObject:cmdContent];
        if (netDataArray.count <= 1) {
            [self openStream];
        }
    }
}
-(void)stopc2sPing{
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(c2sPing) object:nil];
}
-(void)sendArrayCmd:(NSArray*)array{
    double delayTime = 0.0;
    [Global enableVibrate];
    for (DelayInfo *delayInfo in array) {
        NSNumber *number = delayInfo.time;
        delayTime = [number doubleValue]+delayTime;
        [self performSelector:@selector(sendCmd:) withObject:delayInfo.app_cmd afterDelay:delayTime];
    }
}
-(void)sendCmd: (NSString *)cmd{
//    NSLog(@"X____________XXXXX______");
    [[PokerControlClient share] startCmd:@"5" code:cmd];
}
-(void)recvStr:(NSString*)str{

    if (netDataArray.count > 0) {
        [self openStream];
    }
    
    NSMutableString *mutstr = [NSMutableString stringWithString:str];
    NSRange range = [str rangeOfString:@"<wifi_data code=\""];
    NSRange range1 = [str rangeOfString:@"<wifi_data temp=\""];
    NSRange rangeSocket = [str rangeOfString:@"status_f=\""];
    if (range.location != NSNotFound) {//温度
        NSString *nextstr = [mutstr substringFromIndex:range.location+range.length];
    
        NSRange nextrange = [nextstr rangeOfString:@"\""];
        nextstr = [nextstr substringToIndex:nextrange.location];
        
//        NSString *str = [NSString stringWithFormat:@"%@_%@", [[IDGenerator share] genID], nextstr];
        
        [NC postNotificationName:NOTI_TEMP_INFO object:nextstr];
        
        //CONNECT_WIFI 收到心跳包
        [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(c2sPing) object:nil];
        
        NSLog(@"code  %@ ", nextstr);
        
    }else if (range1.location != NSNotFound) {
        
//        [NC postNotificationName:CONNECT_WIFI object:nil]; //CONNECT_WIFI 收到心跳包
        
        if (!beginStudy) {
            [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(c2sPing) object:nil];
        }
    }else if(rangeSocket.location != NSNotFound){
        NSString *nextstr = [mutstr substringWithRange:NSMakeRange(rangeSocket.location+10, 1)];
        [NC postNotificationName:NOTI_SWITCH_INFO object:[nextstr substringToIndex:1]];
    }
    NSLog(@"");
}
#pragma mark
//连接成功后
-(void)didConnect {
    NSLog(@"didConnect");
    if ([self.ctrlPort intValue] == import_port) {//导入数据的时候特殊处理
        NSString *content = @"<data><cmd>1001</cmd></data>";
        [netEventHandler sendString:content];
    }
    else if (netDataArray.count > 0) {
        NSString *content = [netDataArray objectAtIndex:0];
        [netEventHandler sendString:content];
        [netDataArray removeObjectAtIndex:0];
    }
}
-(void)openImportStream {
    
//    self.ctrlIP = @"192.168.200.42";//test
//    self.ctrlPort = @"18004";
    
    NSLog(@"openStream %@: %@", self.ctrlIP, ctrlPort);
    
    [netEventHandler connectToHost:ctrlIP onPort:[ctrlPort intValue]];
}
-(void)startServer:(UInt16)port{
    NSLog(@"startServer %d", port);
    [netEventHandler acceptOnPort:port];
}
-(void)streamDidOpen:(DDXMLElement *)root{
    
}
-(void)loginFail:(DDXMLElement*)failElement {//登录失败
    NSString *error = nil;
    if ([failElement childCount]>0) {
        error = [[failElement childAtIndex:0] stringValue];
    }
    if (error == nil) {//不能为nil, 为nil会被认为登录成功。
        error = @"error";
    }
    if ([failElement elementForName:@"not-authorized"]) {
        //用户名密码校验失败，取消自动重连
        error = @"not-authorized";
    }
    NSLog(@"登录失败。错误信息：%@", error);
}
-(void)didReadElement:(DDXMLElement*)xmlElement{
    if (xmlElement) {
        if ([@"cmd" isEqualToString:xmlElement.name]) {
            //            NSLog(@"cmd");
        }else if ([@"device" isEqualToString:xmlElement.name]) {
            NSArray *itemElements = [xmlElement elementsForName:@"device_item"];
            NSMutableDictionary *newDic = [[NSMutableDictionary alloc] init];
            NSMutableDictionary *newDic1 = [[NSMutableDictionary alloc] init];
            
            for (DDXMLElement *itemElement in itemElements) {
                NSString *deviceid = [itemElement attributeStringValueForName:@"id"];
                //                NSString *deviceicon = [itemElement attributeStringValueForName:@"icon"];
                NSString *devicetype = [itemElement attributeStringValueForName:@"type"];
                NSString *devicename = [itemElement attributeStringValueForName:@"name"];
                if ([devicetype isEqualToString:@"remote"]) {
                    [newDic setValue:@"ipaddr" forKey:deviceid];
                    [UD setObject:newDic forKey:LANIPAddress_list];
                }else if ([devicetype isEqualToString:@"socket"]) {
                    
                    [newDic1 setValue:@"ipaddr" forKey:deviceid];
                    [UD setObject:newDic1 forKey:LAN_SOCKET_IPAddress_list];
                }
                [UD synchronize];
                NSLog(@"devicetype %@ %@", devicetype, devicename);
            }
        }else if ([@"remote" isEqualToString:xmlElement.name]) {
            NSArray *itemElements = [xmlElement elementsForName:@"remote_item"];
            BOOL isDelete = NO;
            for (DDXMLElement *itemElement in itemElements) {
                NSString *deviceid = [itemElement attributeStringValueForName:@"device_id"];
                NSString *remote_id = [itemElement attributeStringValueForName:@"remote_id"];
                NSString *devicetype= [itemElement attributeStringValueForName:@"type"];
                NSString *name = [itemElement attributeStringValueForName:@"name"];
                [remote_idDic setObject:devicetype forKey:[NSString stringWithFormat:@"%@_%@", deviceid, remote_id]];
                DEVICE_TYPE curDeviceType = [self stringToEnum:devicetype];
                DeviceInfo *deviceInfo = [[DeviceInfo alloc] initWithType:curDeviceType name:name fileid:nil];
                if (!isDelete) {
                    [[DataManager GetInstance:deviceid] deleteDevice];
                    isDelete = YES;
                }
                [[DataManager GetInstance:deviceid].deviceArray addObject:deviceInfo];
                [[DataManager GetInstance:deviceid] setAllDevices];
            }
        }else if ([@"key" isEqualToString:xmlElement.name]){
            NSArray *itemElements = [xmlElement elementsForName:@"key_item"];
            for (DDXMLElement *itemElement in itemElements) {
                NSString *remote_id = [itemElement attributeStringValueForName:@"remote_id"];
                NSString *deviceid = [itemElement attributeStringValueForName:@"device_id"];
                NSString *tag = [itemElement attributeStringValueForName:@"tag"];
                NSString *name = [itemElement attributeStringValueForName:@"name"];
                NSString *is_combination_key = [itemElement attributeStringValueForName:@"is_combination_key"];
                NSString *keycode1 = [itemElement attributeStringValueForName:@"keycode1"];
                NSString *icon = [itemElement attributeStringValueForName:@"icon"];
                NSString *devicetype = [remote_idDic objectForKey:[NSString stringWithFormat:@"%@_%@", deviceid, remote_id]];
                DEVICE_TYPE curDeviceType = [self stringToEnum:devicetype];
                [[DataManager GetInstance:deviceid] releaseDataManager:deviceid];
                for (DeviceInfo *deviceInfo in [DataManager GetInstance:deviceid].deviceArray) {
                    if (deviceInfo.type == curDeviceType) {
                        if (curDeviceType == DEVICE_CUSTOM) {
                            
                            NSDataInfo *dataInfo = [[NSDataInfo alloc] init];
                            dataInfo.isCustom = YES;
                            dataInfo.isStudy = YES;
                            //组合键
                            if ([is_combination_key boolValue]) {
                                [self dealComboxKey:itemElement dataInfo:dataInfo];
                            }else{
                                dataInfo.app_cmd = keycode1;
                                if (!keycode1) {
                                    dataInfo.isStudy = NO;
                                }
                            }
                            
                            if ([name length] > 0 && ![name isEqualToString:@"null"]) {
                                dataInfo.temp = name;
                            }
                            dataInfo._id = tag;
                            NSInteger screen_width = [[itemElement attributeStringValueForName:@"screen_width"] integerValue];
                            NSInteger screen_height = [[itemElement attributeStringValueForName:@"screen_height"] integerValue];
                            NSInteger frame_x = [[itemElement attributeStringValueForName:@"x"] integerValue];
                            NSInteger frame_y = [[itemElement attributeStringValueForName:@"y"] integerValue];
                            dataInfo.frame_x = frame_x*SCREEN_WIDTH/screen_width+13;
                            dataInfo.frame_y = frame_y*SCREEN_HEIGHT/screen_height-35;
                            dataInfo.type = 0;
                            dataInfo.name = [self androidIconToIphoneIcon:icon];
                            CGRect rect = [NSDataInfo nameToRect:dataInfo.name];
                            dataInfo.frame_w = rect.size.width;
                            dataInfo.frame_h = rect.size.height;
                            [deviceInfo.keyArray addObject:dataInfo];
                            [[DataManager GetInstance:deviceid] setAllDevices];
                        }else{
                            NSInteger curTag = [self androidTagToIphoneTag:[tag integerValue] deviceType:curDeviceType];
                            if (deviceInfo.keyArray.count > curTag && curTag!=-1) {
                                NSDataInfo *dataInfo = [deviceInfo.keyArray objectAtIndex:curTag];
                                if (dataInfo) {
                                    dataInfo.isStudy = YES;
                                    //组合键
                                    if ([is_combination_key boolValue]) {
                                        [self dealComboxKey:itemElement dataInfo:dataInfo];
                                    }else{
                                        dataInfo.app_cmd = keycode1;
                                    }
                                    if ([name length] > 0 && ![name isEqualToString:@"null"] ) {
                                        if (curDeviceType==DEVICE_AIR) {
                                            dataInfo.temp = name;
                                        }else{
                                            dataInfo.btnName = name;
                                        }
                                    }
                                    [[DataManager GetInstance:deviceid] setAllDevices];
                                }
                            }
                        }
                        break;
                    }
                }
            }
            [NC postNotificationName:NOTI_EXPORT_FINISHED object:nil];
        }else if ([@"file" isEqualToString:xmlElement.name]){
            NSLog(@"file");
        }else{
            NSLog(@"didReadElement:%@",[xmlElement name]);
        }
    }
}
-(void)dealComboxKey:(DDXMLElement *)itemElement dataInfo:(NSDataInfo*)dataInfo{
    NSString *keycode1 = [itemElement attributeStringValueForName:@"keycode1"];
    float delay1 = [[itemElement attributeStringValueForName:@"delay1"] floatValue];
    NSString *keycode2 = [itemElement attributeStringValueForName:@"keycode2"];
    float delay2 = [[itemElement attributeStringValueForName:@"delay2"] floatValue];
    NSString *keycode3 = [itemElement attributeStringValueForName:@"keycode3"];
    float delay3 = [[itemElement attributeStringValueForName:@"delay3"] floatValue];
    NSString *keycode4 = [itemElement attributeStringValueForName:@"keycode4"];
    float delay4 = [[itemElement attributeStringValueForName:@"delay4"] floatValue];
    NSString *keycode5 = [itemElement attributeStringValueForName:@"keycode5"];
    float delay5 = [[itemElement attributeStringValueForName:@"delay5"] floatValue];
    NSString *keycode6 = [itemElement attributeStringValueForName:@"keycode6"];
    for (int i=0; i<6; i++) {
        DelayInfo *delayInfo = [[DelayInfo alloc] init];
        if (i == 0) {
            delayInfo.app_cmd = keycode1;
            delayInfo.time = [NSNumber numberWithFloat:1];
        }else if (i == 1) {
            delayInfo.app_cmd = keycode2;
            delayInfo.time = [NSNumber numberWithFloat:delay1];
        }else if (i == 2) {
            delayInfo.app_cmd = keycode3;
            delayInfo.time = [NSNumber numberWithFloat:delay2];
        }else if (i == 3) {
            delayInfo.app_cmd = keycode4;
            delayInfo.time = [NSNumber numberWithFloat:delay3];
        }else if (i == 4) {
            delayInfo.app_cmd = keycode5;
            delayInfo.time = [NSNumber numberWithFloat:delay4];
        }else if (i == 5) {
            delayInfo.app_cmd = keycode6;
            delayInfo.time = [NSNumber numberWithFloat:delay5];
        }
        [dataInfo.array addObject:delayInfo];
    }
}
-(NSString*)androidIconToIphoneIcon:(NSString*)icon{
    NSString *iPhoneIcon = nil;
    if ([icon hasSuffix:@"custom_left_unstudy"]) {
        iPhoneIcon = @"custom_left";
    }else if ([icon hasSuffix:@"custom_right_unstudy"]) {
        iPhoneIcon = @"custom_right";
    }else if ([icon hasSuffix:@"custom_up_unstudy"]) {
        iPhoneIcon = @"custom_up";
    }else if ([icon hasSuffix:@"custom_down_unstudy"]) {
        iPhoneIcon = @"custom_down";
    }
    else if ([icon hasSuffix:@"ok_unstudy"]) {
        iPhoneIcon = @"custom_ok";
    }else if ([icon hasSuffix:@"power_unstudy"]) {
        iPhoneIcon = @"open";
    }else if ([icon hasSuffix:@"custom_add_unstudy"]) {
        iPhoneIcon = @"custom_plus";
    }else if ([icon hasSuffix:@"custom_rd_unstudy"]) {
        iPhoneIcon = @"custom_reduce";
    }
    else if ([icon hasSuffix:@"custom_vadd_unstudy"]) {
        iPhoneIcon = @"custom_volume_large";
    }else if ([icon hasSuffix:@"custom_vrd_unstudy"]) {
        iPhoneIcon = @"custom_volume_small";
    }else if ([icon hasSuffix:@"power_off_unstudy"]) {
        iPhoneIcon = @"custom_off";
    }else if ([icon hasSuffix:@"power_on_unstudy"]) {
        iPhoneIcon = @"custom_on";
    }
    else if ([icon hasSuffix:@"home_unstudy"]) {
        iPhoneIcon = @"tv_home_button";
    }else if ([icon hasSuffix:@"mute_unstudy"]) {
        iPhoneIcon = @"mute_button";
    }else if ([icon hasSuffix:@"back_unstudy"]) {
        iPhoneIcon = @"back_button";
    }else if ([icon hasSuffix:@"av_tv_unstudy"]) {
        iPhoneIcon = @"AV_button";
    }
    
    return iPhoneIcon;
}
-(NSInteger)androidTagToIphoneTag:(NSInteger)tag deviceType:(DEVICE_TYPE)deviceType{
    if (deviceType == DEVICE_AIR) {
        if (tag == 1) {
            return 0;
        }else if (tag == 6) {
            return 1;
        }else if (tag == 2) {
            return tag;
        }else if (tag == 3) {
            return tag;
        }else if (tag == 4) {
            return 5;
        }
    }else if (deviceType==DEVICE_TV || deviceType==DEVICE_STB) {//中间五个+右边2个
        if (tag == 5) {
            return 8;
        }else if (tag == 6) {
            return 9;
        }else if (tag == 7) {
            return 6;
        }else if (tag == 8) {
            return 7;
        }else if (tag == 9) {
            return 10;
        }else if (tag == 10) {
            return 4;
        }else if (tag == 11) {
            return 5;
        }else {
            return tag-1;
        }
    }else if (deviceType == DEVICE_SOUND) {//中间五个不一样
        if (tag == 3) {
            return 4;
        }else if (tag == 4) {
            return 5;
        }else if (tag == 5) {
            return 2;
        }else if (tag == 6) {
            return 3;
        }else if (tag == 7) {
            return 6;
        }else {
            return tag-1;
        }
    }else if (deviceType == DEVICE_SOCKET3) {
        if (tag == 4) {
            return 1;
        }else if (tag == 2) {
            return 2;
        }else if (tag == 3) {
            return 3;
        }else if (tag == 1) {
            return 0;
        }
    }else if (deviceType==DEVICE_SOCKET2 || deviceType==DEVICE_SOCKET1) {
        return tag-1;
    }
    return -1;
}
-(DEVICE_TYPE)stringToEnum:(NSString*)devicetype{
    DEVICE_TYPE curDeviceType = DEVICE_TV;
    if ([devicetype isEqualToString:@"TV"]) {//电视
        curDeviceType = DEVICE_TV;
    }else if ([devicetype isEqualToString:@"AIR_CONDITION"]) {//空调
        curDeviceType = DEVICE_AIR;
    }else if ([devicetype isEqualToString:@"STB"]) {//机顶盒
        curDeviceType = DEVICE_STB;
    }else if ([devicetype isEqualToString:@"MUSIC"]) {//音响
        curDeviceType = DEVICE_SOUND;
    }else if ([devicetype isEqualToString:@"COTSTOM"]) {//自定义
        curDeviceType = DEVICE_CUSTOM;
    }else if ([devicetype isEqualToString:@"XIAO_MI_BOX"]) {//小米盒子
        curDeviceType = DEVICE_XIAOMI;
    }else if ([devicetype isEqualToString:@"ITV"]) {//appletv
        curDeviceType = DEVICE_APPLETV;
    }else if ([devicetype isEqualToString:@"RF_ONE_KEY"]) {//插座1
        curDeviceType = DEVICE_SOCKET1;
    }else if ([devicetype isEqualToString:@"RF_TWO_KEY"]) {//插座2
        curDeviceType = DEVICE_SOCKET2;
    }else if ([devicetype isEqualToString:@"RF_THREE_KEY"]) {//插座3
        curDeviceType = DEVICE_SOCKET3;
    }
    return curDeviceType;
}
-(void)didDisconnect{
}
-(void)networkStateChanged{
}

#pragma mark user motherd

//购买筹码
-(void)cbuychip:(NSInteger)count{
    DDXMLElement *cbuychipElement=[DDXMLElement elementWithName:@"cbuychip"];
//    [cbuychipElement addAttributeWithName:@"id" stringValue:[[IDGenerator share] genID]];
    DDXMLElement *expectchip=[DDXMLElement elementWithName:@"expectchip" stringValue:[NSString stringWithFormat:@"%d",count]];
    [cbuychipElement addChild:expectchip];
    [netEventHandler sendElement:cbuychipElement];
}
@end
